package cn.gbase.jiangsu.data.transfer.service;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.util.ArrayList;
import java.util.List;

import org.nutz.dao.Cnd;
import org.nutz.dao.ConnCallback;
import org.nutz.dao.Dao;
import org.nutz.dao.QueryResult;
import org.nutz.dao.pager.Pager;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.service.IdEntityService;

import cn.gbase.jiangsu.data.transfer.bean.ProductSortTree;
import cn.gbase.jiangsu.data.transfer.bean.ProductSortTreeNode;
import cn.gbase.jiangsu.data.transfer.common.Constants;
import cn.gbase.jiangsu.data.transfer.common.SystemException;

@IocBean(args = { "refer:dao" })
public class ProductSortTreeService extends IdEntityService<ProductSortTree> {

	@Inject
	private ProductSortTreeNodeService productSortTreeNodeService;

	public ProductSortTreeService() {
		super();
	}

	public ProductSortTreeService(Dao dao) {
		super(dao);
	}

	/**
	 * 取得所有标准框架列表.
	 * 
	 * @return
	 */
	public List<ProductSortTree> getStandTreeList() {
		return this.dao()
				.query(ProductSortTree.class, Cnd.wrap(" order by id"));
	}

	public String getAllTreePulldownList() {
		StringBuilder builder = new StringBuilder();

		List<ProductSortTree> treeList = this.dao().query(
				ProductSortTree.class, Cnd.wrap(" order by id"));
		for (ProductSortTree tree : treeList) {
			builder.append("<option value='tree");
			builder.append(tree.getId());
			builder.append("'>");
			builder.append(tree.getName());
			builder.append("</option>");

			addTreeNode(builder, tree.getId());
		}
		return builder.toString();
	}

	private void addTreeNode(StringBuilder builder, int treeId) {
		List<ProductSortTreeNode> treeList = this.dao().query(
				ProductSortTreeNode.class,
				Cnd.wrap("pid>0 and treeId=" + treeId));
		for (ProductSortTreeNode treeNode : treeList) {
			builder.append("<option value='node");
			builder.append(treeNode.getId());
			builder.append("'>");
			builder.append(treeNode.getLevelName());
			builder.append("</option>");
		}
	}

	/**
	 * 取得标准框架列表（分页查询）.
	 * 
	 * @return
	 */
	public QueryResult getStandTreeList(int pageNumber, String name) {
		if (pageNumber <= 0) {
			pageNumber = 1;
		}

		// 拼接条件
		String cond = "1=1";
		if (name != null && name.length() > 0) {
			name = name.replace("'", "");
			cond += " and name like '%" + name + "%' ";
		}
		Pager pager = this.dao().createPager(pageNumber,
				Constants.LIST_ONE_PAGE_SIZE);

		// 查询记录总数
		int recordCount = this.dao().count(ProductSortTree.class,
				Cnd.wrap(cond));
		pager.setRecordCount(recordCount);

		// 没数据，直接返回
		if (recordCount == 0) {
			return new QueryResult(new ArrayList<ProductSortTree>(0), pager);
		}

		// 计算页数
		int maxPageNumber = 0;
		if (recordCount % Constants.LIST_ONE_PAGE_SIZE == 0) {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE;
		} else {
			maxPageNumber = recordCount / Constants.LIST_ONE_PAGE_SIZE + 1;
		}
		if (pageNumber > maxPageNumber) {
			pager.setPageNumber(maxPageNumber);
		}

		// 查询
		List<ProductSortTree> resultList = this.dao().query(
				ProductSortTree.class, Cnd.wrap(cond), pager); // 当前页面显示记录

		// 返回
		return new QueryResult(resultList, pager);
	}

	public boolean addOrUpdStandTree(ProductSortTree tree) {
		if (tree.getId() > 0) {
			this.dao().update(tree);
		} else {
			this.dao().insert(tree);

			// 树的根节点
			ProductSortTreeNode root = new ProductSortTreeNode();
			root.setTreeId(tree.getId());
			root.setCode("root");
			root.setName("根节点");
			productSortTreeNodeService.addStandTreeRootNode(root);
		}
		return true;
	}

	public ProductSortTree getStandTree(int treeId) {
		return this.dao().fetch(ProductSortTree.class, treeId);
	}

	public void deleteStandTree(final int treeId) {
		this.dao().run(new ConnCallback() {
			public void invoke(Connection conn) throws Exception {

				CallableStatement callStmt = null;
				try {
					callStmt = conn.prepareCall("{call deleteTree(?,?,?)}");
					callStmt.setInt(1, treeId);
					callStmt.registerOutParameter(2, java.sql.Types.INTEGER);
					callStmt.registerOutParameter(3, java.sql.Types.VARCHAR);
					callStmt.executeUpdate();

					// 返回值
					int code = callStmt.getInt(2);
					if (code != 1000) {
						String msg = callStmt.getString(3);
						throw new SystemException(msg);
					}
				} finally {
					if (null != callStmt) {
						callStmt.close();
					}
				}
			}
		});
	}

	public String getTreeJsonDataForECOTree(int treeId) {
		StringBuilder builder = new StringBuilder();
		builder.append("[");

		// pid=0的也检索出来，作为根节点
		List<ProductSortTreeNode> treeList = this.dao().query(
				ProductSortTreeNode.class, Cnd.wrap("treeId=" + treeId));
		for (ProductSortTreeNode treeNode : treeList) {
			if (treeNode.getPid() == 0) {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pid:-1"); // 固定-1
				builder.append(",name:'");
				builder.append(getStandTree(treeId).getName() + "("
						+ treeNode.getLinkProductCount() + ")"); // 树的名字
				builder.append("'}");
			} else {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pid:");
				builder.append(treeNode.getPid());
				builder.append(",name:'");
				builder.append(treeNode.getName() + "("
						+ treeNode.getLinkProductCount() + ")");
				builder.append("'}");
			}
			builder.append(",");
		}
		builder.deleteCharAt(builder.length() - 1);
		builder.append("]");

		// [{id:1,pid:-1,name:'xx'},{id:2,pid:1,name:'yy'}]
		return builder.toString();
	}

	/**
	 * 生成单树的JSON数据，ZTree格式.
	 * 
	 * @param treeId
	 *            树ID
	 * @return JSON变量的数据
	 */
	public String getTreeJsonDataForZTree(int treeId) {
		StringBuilder builder = new StringBuilder();
		builder.append("[");
		addOneTreeChildren(treeId, builder);
		builder.append("]");

		// [{id:1,pid:-1,name:'xx'},{id:2,pid:1,name:'yy'}]
		return builder.toString();
	}

	private void addOneTreeChildren(int treeId, StringBuilder builder) {

		// pid=0的也检索出来，作为根节点
		List<ProductSortTreeNode> nodeList = this.dao().query(
				ProductSortTreeNode.class, Cnd.wrap("treeId=" + treeId));
		for (ProductSortTreeNode treeNode : nodeList) {
			if (treeNode.getPid() == 0) {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pId:0"); // 固定0
				builder.append(",name:'");
				builder.append(getStandTree(treeId).getName() + "("
						+ treeNode.getLinkProductCount() + ")"); // 树的名字
				builder.append("'}");
			} else {
				builder.append("{id:");
				builder.append(treeNode.getId());
				builder.append(",pId:");
				builder.append(treeNode.getPid());
				builder.append(",name:'");
				builder.append(treeNode.getName());
				builder.append("(");
				builder.append(treeNode.getLinkProductCount());
				builder.append(")");
				builder.append("'}");
			}
			builder.append(",");
		}
		if (nodeList.size() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
	}

	public String getAllTreeJsonDataForZTree() {
		StringBuilder builder = new StringBuilder();
		builder.append("[");

		// 添加所有树的节点
		List<ProductSortTree> treeList = this.dao().query(
				ProductSortTree.class, Cnd.wrap(" order by id"));
		for (ProductSortTree tree : treeList) {
			addOneTreeChildren(tree.getId(), builder);
			builder.append(",");
		}
		if (treeList.size() > 0) {
			builder.deleteCharAt(builder.length() - 1);
		}
		builder.append("]");
		return builder.toString().replace(",,", ",");
	}

	/**
	 * 根据服务中心ID取得对应的树.
	 * 
	 * @param id
	 *            社区ID
	 */
	public ProductSortTree getTreeByCommId(int id) {

		List<ProductSortTree> treeList = this.dao().query(
				ProductSortTree.class, Cnd.where("company", "=", id));
		if (treeList.size() == 0) {
			return null;
		}
		return treeList.get(0);
	}
}
